package com.qiyun.dinghuohui.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.qiyun.dinghuohui.ApplicationDataHolder;
import com.qiyun.dinghuohui.common.Preferences;

/**
 * Created by xlm on 2018\5\25 0025
 */
public class PreferenceUtil {

    /**
     * 保存任意类型的数据
     *
     * @param key
     * @param object
     */
    public static void setParam(String key, Object object) {
        SharedPreferences sp = ApplicationDataHolder.getApp().getApplicationContext()
                .getSharedPreferences(Preferences.PREFERENCE_FILE_NAME,
                        Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        }
        editor.apply();
    }

    /**
     * 获取保存的数据
     *
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object getParam(String key, Object defaultObject) {
        SharedPreferences sp = ApplicationDataHolder.getApp().getApplicationContext()
                .getSharedPreferences(Preferences.PREFERENCE_FILE_NAME,
                        Context.MODE_PRIVATE);
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }
        return null;
    }
}
